package hk.linkcredit.walletservice.rocketmq;

import hk.linkcredit.common.rocketmq.util.RocketMqUtils;
import hk.linkcredit.walletservice.rocketmq.example.WalletExampleDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

@Slf4j
@SpringBootApplication
public class WalletExampleProducer {
    public static void main(String[] args) {
        Properties props = System.getProperties();
        props.setProperty("server.port","9999");
        props.setProperty("rocketmq.name-server","192.168.1.179:9876");
        props.setProperty("rocketmq.producer.group","example-producer");
        SpringApplication springApplication = new SpringApplication();
        springApplication.setDefaultProperties(props);
        ApplicationContext applicationContext = springApplication.run(WalletExampleProducer.class, args);
        WalletExampleProducer exampleProducer = (WalletExampleProducer)applicationContext.getBean("walletExampleProducer");
        RocketMQTemplate rocketMQTemplate = (RocketMQTemplate)applicationContext.getBean("rocketMQTemplate");
        exampleProducer.sendMessageInTransaction(rocketMQTemplate);
    }

    public void sendMessageInTransaction(RocketMQTemplate rocketMQTemplate) {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        //主题名+tag
        String topic = "example-topic";
        //消息内容
        String msg = "{ \"msgId\": \"1539466538035326979\", \"reference\":\"23\", \"custNo\": \"20220527636202569730\", \"amount\": 10.00, \"fundsType\": \"1\" }";
        //生成消息唯一标识，用于检查本地事务是否执行成功
        String msgId = (new UUID(random.nextLong(), random.nextLong())).toString().replace("-", "");
        //业务id,订单id之类的
        String bizId = "1539466538035326999";
        //执行本地事务需要用到的参数
        WalletExampleDTO walletExampleDTO = new WalletExampleDTO();
        walletExampleDTO.setExampleId(123L);
        walletExampleDTO.setRemark("本地事务插入数据");
        RocketMqUtils.sendMessageInTransaction(rocketMQTemplate,topic,msg,msgId,bizId,"walletExampleTransactionHandler",walletExampleDTO);
    }
}
